<template>
  <el-dialog
    title="班级结算"
    :visible.sync="visible"
    width="1200px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 收入项区域 -->
    <div class="settlement-section">
      <h3 class="section-title">收入项</h3>
      <el-table
        :data="incomeItems"
        border
        size="mini"
        class="settlement-table"
      >
        <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
        <el-table-column label="培训费用项目" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.project"
              placeholder="请选择费用项目"
              style="width: 100%"
              @change="handleFieldChange(scope.row)"
            >
              <el-option
                v-for="dict in costProjectDict"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
              <el-option
                v-if="!costProjectDict || costProjectDict.length === 0"
                :key="'-1'"
                :label="'- 暂无费用项目，请先在字典管理中配置 -'"
                :value="''"
                disabled
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center">
          <template #default="scope">
            <el-input
              v-model.number="scope.row.quantity"
              placeholder="请输入数量"
              type="number"
              min="0"
              style="width: 100%"
              @input="handleFieldChange(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center">
          <template #default="scope">
            <el-input
              v-model.number="scope.row.price"
              placeholder="请输入单价"
              type="number"
              min="0"
              step="0.01"
              style="width: 100%"
              @input="handleFieldChange(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="小计" align="center">
          <template #default="scope">
            {{ formatCurrency(scope.row.subtotal || 0) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template #default="scope">
            <el-input
              v-model="scope.row.remark"
              placeholder="请输入备注"
              style="width: 100%"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button
              type="text"
              size="mini"
              @click="saveItem('income', scope.row)"
            >
              保存
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="removeItem('income', scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 收入合计 -->
      <div class="total-row">
        <span class="total-label">合计：</span>
        <span class="total-value">{{ formatCurrency(incomeTotal) }}</span>
      </div>

      <!-- 添加收入项 -->
      <el-button
        type="text"
        class="add-item-btn"
        @click="addItem('income')"
      >
        <i class="el-icon-plus"></i> 添加一项内容
      </el-button>
    </div>

    <!-- 支出项区域 -->
    <div class="settlement-section">
      <h3 class="section-title">支出项</h3>
      <el-table
        :data="expenseItems"
        border
        size="mini"
        class="settlement-table"
      >
        <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
        <el-table-column label="培训费用项目" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.project"
              placeholder="请选择费用项目"
              style="width: 100%"
              @change="handleFieldChange(scope.row)"
            >
              <el-option
                v-for="dict in costProjectDict"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
              <el-option
                v-if="!costProjectDict || costProjectDict.length === 0"
                :key="'-1'"
                :label="'- 暂无费用项目，请先在字典管理中配置 -'"
                :value="''"
                disabled
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center">
          <template #default="scope">
            <el-input
              v-model.number="scope.row.quantity"
              placeholder="请输入数量"
              type="number"
              min="0"
              style="width: 100%"
              @input="handleFieldChange(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center">
          <template #default="scope">
            <el-input
              v-model.number="scope.row.price"
              placeholder="请输入单价"
              type="number"
              min="0"
              step="0.01"
              style="width: 100%"
              @input="handleFieldChange(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="小计" align="center">
          <template #default="scope">
            {{ formatCurrency(scope.row.subtotal || 0) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template #default="scope">
            <el-input
              v-model="scope.row.remark"
              placeholder="请输入备注"
              style="width: 100%"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80">
          <template #default="scope">
            <el-button
              type="text"
              size="mini"
              @click="saveItem('expense', scope.row)"
            >
              保存
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="removeItem('expense', scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 支出合计 -->
      <div class="total-row">
        <span class="total-label">合计：</span>
        <span class="total-value">{{ formatCurrency(expenseTotal) }}</span>
      </div>

      <!-- 添加支出项 -->
      <el-button
        type="text"
        class="add-item-btn"
        @click="addItem('expense')"
      >
        <i class="el-icon-plus"></i> 添加一项内容
      </el-button>
    </div>

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <!-- <el-button @click="resetData">重置</el-button> -->
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  listClassPaymentSettlement,
  addClassPaymentSettlement,
  updateClassPaymentSettlement,
  delClassPaymentSettlement
} from "@/api/training/classPaymentSettlement.js";

export default {
  name: 'classSettlementDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    classId: {
      type: String,
      default: ""
    },
    settlementId: {
      type: String,
      default: ""
    }
  },
  dicts: ["training_cost_project"],
  data() {
    return {
      costProjectDict: [],
      incomeItems: [],
      expenseItems: [],
      originalIncomeItems: [],
      originalExpenseItems: [],
      originalCostProjectDict: []
    }
  },
  computed: {
    incomeTotal() {
      return this.incomeItems.reduce((total, item) => total + (item.subtotal || 0), 0)
    },
    expenseTotal() {
      return this.expenseItems.reduce((total, item) => total + (item.subtotal || 0), 0)
    }
  },
  created() {
    // this.loadDictData();
    // this.getList();
  },
  watch:{
    classId:{
      handler(newVal){
        this.incomeItems = [];
      this.expenseItems = [];
        this.loadDictData();
        this.getList();
      }
      
    }
  },
  methods: {
    // 加载字典数据（不变）
    loadDictData() {
      this.costProjectDict = (this.dict && this.dict.type && this.dict.type.training_cost_project) || [];
      this.originalCostProjectDict = JSON.parse(JSON.stringify(this.costProjectDict));
    },

    // 获取结算列表数据（不变）
    async getList() {
      try {
        const res = await listClassPaymentSettlement({
          trainingClassId: this.classId
        });
        if (res.code === 200) {
          this.incomeItems = [];
          this.expenseItems = [];

          res.rows.forEach(backendItem => {
            const frontItem = {
              id: backendItem.classPaymentSettlementId,
              project: backendItem.trainingCostProject,
              quantity: backendItem.num,
              price: backendItem.price,
              subtotal: backendItem.cost,
              remark: backendItem.remark || ""
            };

            if (backendItem.costType === "2") {
              this.incomeItems.push(frontItem);
            } else if (backendItem.costType === "1") {
              this.expenseItems.push(frontItem);
            }
          });

          if (this.incomeItems.length === 0) {
            this.incomeItems.push(this.createEmptyItem());
          }
          if (this.expenseItems.length === 0) {
            this.expenseItems.push(this.createEmptyItem());
          }

          this.originalIncomeItems = JSON.parse(JSON.stringify(this.incomeItems));
          this.originalExpenseItems = JSON.parse(JSON.stringify(this.expenseItems));
        } else {
          this.$message.error(`结算数据加载失败：${res.msg}`);
        }
      } catch (err) {
        this.$message.error("结算列表接口调用失败");
        console.error("列表加载错误：", err);
      }
    },

    // 创建空数据项（不变）
    createEmptyItem() {
      return {
        id: `temp_${Math.random().toString(36).substr(2, 9)}`,
        project: "",
        quantity: null,
        price: null,
        subtotal: 0,
        remark: ""
      };
    },

    // 格式化金额（不变）
    formatCurrency(amount) {
      return '¥' + Number(amount).toFixed(2);
    },

    // 计算小计（不变）
    handleFieldChange(item) {
      if (item.quantity !== null && item.price !== null && item.quantity >= 0 && item.price >= 0) {
        item.subtotal = item.quantity * item.price;
      } else {
        item.subtotal = 0;
      }
    },

    // 添加数据项（不变）
    addItem(type) {
      const targetList = type === 'income' ? this.incomeItems : this.expenseItems;
      targetList.push(this.createEmptyItem());
    },

    // 删除数据项（不变）
    async removeItem(type, index) {
      const targetList = type === 'income' ? this.incomeItems : this.expenseItems;
      const item = targetList[index];

      // 临时数据直接删除
      if (item.id.includes('temp_')) {
        targetList.splice(index, 1);
        this.$message.success('已删除');
        return;
      }

      // 后端数据调用删除接口
      try {
        const res = await delClassPaymentSettlement(item.id);
        if (res.code === 200) {
          this.$message.success('删除成功');
          targetList.splice(index, 1);
          // 同步删除原始数据中的对应项
          const originalList = type === 'income' ? this.originalIncomeItems : this.originalExpenseItems;
          const originalIndex = originalList.findIndex(orig => orig.id === item.id);
          if (originalIndex > -1) originalList.splice(originalIndex, 1);
        } else {
          this.$message.error(`删除失败：${res.msg || '操作异常'}`);
        }
      } catch (err) {
        this.$message.error('删除接口调用失败');
        console.error('删除错误：', err);
      }
    },

    // 【核心修改】保存按钮直接调用接口（支持新增/更新单条数据）
    async saveItem(type, item) {
      // 1. 基础校验
      if (!item.project) {
        this.$message.error('请选择费用项目');
        return;
      }
      if (item.quantity === null || item.quantity <= 0) {
        this.$message.error('请输入有效的数量（大于0）');
        return;
      }
      if (item.price === null || item.price <= 0) {
        this.$message.error('请输入有效的单价（大于0）');
        return;
      }

      // 2. 构造单条提交参数（适配接口批量格式，仅传当前数据）
      // const submitParams = {
      //   trainingClassId: this.classId,
      //   totalIncome: type === 'income' ? item.subtotal : 0,
      //   totalExpense: type === 'expense' ? item.subtotal : 0,
      //   netProfit: (type === 'income' ? item.subtotal : 0) - (type === 'expense' ? item.subtotal : 0),
      //   incomeList: [],
      //   expenseList: []
      // };

      // 组装当前数据项
      console.log(this.classId)
      const itemToSubmit = {
        classPaymentSettlementId: item.id.includes('temp_') ? null : item.id,
        trainingCostProject: item.project,
        trainingClassId:this.classId,
        num: item.quantity,
        price: item.price,
        cost: item.subtotal,
        costType: type === 'income' ? '2' : '1',
        remark: item.remark || ''
      };
      // type === 'income' ? submitParams.incomeList.push(itemToSubmit) : submitParams.expenseList.push(itemToSubmit);

      try {
        let res;
        // 3. 区分新增（临时ID）和更新（真实ID）
        if (item.id.includes('temp_')) {
          // 新增：调用添加接口
          res = await addClassPaymentSettlement(itemToSubmit);
          if (res.code === 200) {
            // 关键：用后端返回的真实ID替换临时ID（需根据实际接口返回调整字段）
            item.id = res.data?.classPaymentSettlementId || item.id;
            this.$message.success(`${type === 'income' ? '收入项' : '支出项'}新增成功`);
          }
        } else {
          // 更新：调用修改接口
          res = await updateClassPaymentSettlement(itemToSubmit);
          if (res.code === 200) {
            this.$message.success(`${type === 'income' ? '收入项' : '支出项'}保存成功`);
          }
        }

        // 4. 同步更新原始数据（确保重置功能有效）
        if (res?.code === 200) {
          const originalList = type === 'income' ? this.originalIncomeItems : this.originalExpenseItems;
          const targetIndex = originalList.findIndex(orig => orig.id === item.id);

          if (targetIndex > -1) {
            // 更新已有数据
            originalList[targetIndex] = JSON.parse(JSON.stringify(item));
          } else {
            // 新增数据追加到原始列表
            originalList.push(JSON.parse(JSON.stringify(item)));
          }
        }
      } catch (err) {
        this.$message.error(`${type === 'income' ? '收入项' : '支出项'}保存接口调用失败`);
        console.error('保存错误：', err);
      }
    },

    // 重置数据（不变）
    resetData() {
      this.incomeItems = JSON.parse(JSON.stringify(this.originalIncomeItems));
      this.expenseItems = JSON.parse(JSON.stringify(this.originalExpenseItems));
      // this.incomeItems = JSON.parse(JSON.stringify(this.originalIncomeItems));
      // this.expenseItems = JSON.parse(JSON.stringify(this.originalExpenseItems));
      // this.costProjectDict = JSON.parse(JSON.stringify(this.originalCostProjectDict));
    },

    // 【调整】确定按钮仅校验+关闭弹窗（数据已通过保存提交）
    async handleConfirm() {
      // 基础校验：确保无未完善的无效数据
      const hasInvalidIncome = this.incomeItems.some(item =>
        !item.project || item.quantity === null || item.quantity <= 0 || item.price === null || item.price <= 0
      );
      const hasInvalidExpense = this.expenseItems.some(item =>
        !item.project || item.quantity === null || item.quantity <= 0 || item.price === null || item.price <= 0
      );

      // if (hasInvalidIncome || hasInvalidExpense) {
      //   this.$message.error('请完善所有项目的必填信息');
      //   return;
      // }

      this.visible = false;
      this.$emit('confirm');
      this.resetData();
    },

    // 关闭弹窗（不变）
    handleClose() {
      this.resetData();
      this.incomeItems = [];
      this.expenseItems = [];
      this.$emit('close', false);
    }
  }
}
</script>

<style scoped>
.settlement-section {
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

.section-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.settlement-table {
  margin-bottom: 10px;
}

.total-row {
  text-align: right;
  padding: 5px 0;
  font-weight: 500;
  color: #333;
}

.total-label {
  margin-right: 10px;
}

.total-value {
  color: #1890ff;
}

.add-item-btn {
  margin-top: 5px;
  color: #1890ff;
}

.dialog-footer {
  text-align: right;
}
</style>
